package com.dengyuanke.wx.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.dengyuanke.common.result.JsonResult;
import com.dengyuanke.entity.User;
import com.dengyuanke.utils.jwt.JWT;
import com.dengyuanke.utils.jwt.TokenState;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by dengyuanke on 2017/11/8.
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String token=request.getParameter("token");
        Map<String, Object> resultMap= JWT.validToken(token);
        TokenState state=TokenState.getTokenState((String)resultMap.get("state"));
        JsonResult result=new JsonResult();
        switch (state) {
            case VALID:
                //取出payload中数据,放入到request作用域中
                Map data = (Map) resultMap.get("data");
                JSONObject jsonObject = (JSONObject)JSONObject.toJSON(data.get("user"));
                jsonObject.remove("createTime");
                jsonObject.remove("updateTime");
                User currentUser = JSONObject.toJavaObject(jsonObject, User.class);
                request.setAttribute("currentUser", currentUser);
                return true;
            case EXPIRED:
                //token过期，则输出错误信息返回给ajax
                result.setStatus("200");
                result.setSuccess(false);
                result.setMsg("token过期，请重新登录");
                responseMessage(response,result);
               break;
            case INVALID:
                //token过期或者无效，则输出错误信息返回给ajax
                result.setStatus("200");
                result.setSuccess(false);
                result.setMsg("token无效，请重新登录");
                responseMessage(response,result);
                break;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
    //请求不通过，返回错误信息给客户端
    private void responseMessage(HttpServletResponse response, JsonResult result) throws Exception{
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String json = JSONObject.toJSONString(result);
        out.print(json);
        out.flush();
        out.close();
    }
}
